package com.google.code.head2head.gwtmodules.client.login;

import com.google.code.head2head.gwtmodules.client.services.UserInfoService;
import com.google.code.head2head.gwtmodules.client.services.UserInfoServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;

public class H2HLoginPanel extends VerticalPanel{
	
	private String userLoginName;

	private boolean loginValid;
	
	private HTML loginText = new HTML("No user logged");

	public H2HLoginPanel() {
		LoginPanel lp = new LoginPanel(new LoginPanel.LoginListener() {
			public void onSubmit(LoginPanel loginPanel) {
				login(loginPanel.getUsername(), loginPanel.getPassword());
				loginPanel.reset();
			}
		});
		this.add(loginText);
		this.add(lp);
	}

	private void login(final String userLogin, final String userPassword) {

		UserInfoServiceAsync svc = (UserInfoServiceAsync) GWT
				.create(UserInfoService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) svc;
		String moduleRelativeURL = GWT.getModuleBaseURL()
				+ "../userInfoService";
		endpoint.setServiceEntryPoint(moduleRelativeURL);

		AsyncCallback callback = new AsyncCallback() {
			public void onSuccess(Object result) {
				loginValid = ((Boolean) result).booleanValue();
				userLoginName = userLogin;
				if (loginValid) {
					loginText.setHTML("User logged in: " + userLoginName);
				}
			}

			public void onFailure(Throwable ex) {
				Window.alert("Problem logging user");
			}
		};
		// execute the service
		svc.login(userLogin, userPassword, callback);
		
	}

}
